package down;

import android.database.sqlite.SQLiteDatabase;
import android.os.Build;

import androidx.annotation.RequiresApi;

import java.io.File;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import cn.lby.tp.downloadtest.BaseApplication;
import download_temp.FileInfo;
import download_temp.view.OnProgressListener;

public class DownLoaderManger {
    public static String FILE_PATH = BaseApplication.DOWNLOAD_PATH;
    private DownLoaderHelper helper;//数据库帮助类
    private OnProgressListener listener;//进度回调监听
    private Map<String, FileInfo> map = new HashMap<>();//保存正在下载的任务信息
    private static DownLoaderManger manger;


    public void setMap(Map<String, FileInfo> map) {
        this.map = map;
    }

    private DownLoaderManger(DownLoaderHelper helper) {
        this.helper = helper;
    }


    private List<FileInfo> getAllData() {
        return helper.queryAllData(helper.getWritableDatabase());
    }

    // 获取所有下载中的任务
    @RequiresApi(api = Build.VERSION_CODES.N)
    public List<FileInfo> getAllDownloading() {
        List<FileInfo> allData = getAllData();
        return allData.stream()
                .filter(it -> !Utils.isDownLoaded(it))
                .collect(Collectors.toList());
    }


    // 获取所有已下载的任务
    @RequiresApi(api = Build.VERSION_CODES.N)
    public List<FileInfo> getAllDownloaded() {
        return getAllData().stream()
                .filter(Utils::isDownLoaded)
                .collect(Collectors.toList());
    }



    /**
     * 单例模式
     *
     * @param helper   数据库帮助类
     * @return
     */
    public static synchronized DownLoaderManger getInstance(DownLoaderHelper helper) {
        if (manger == null) {
            synchronized (DownLoaderManger.class) {
                if (manger == null) {
                    manger = new DownLoaderManger(helper);
                }
            }
        }
        return manger;
    }

    /**
     * 开始下载任务
     */
    public void start(String url) {
        SQLiteDatabase db = helper.getReadableDatabase();
        FileInfo info = helper.queryData(db, url);
        map.put(url, info);
        //开始任务下载
        // new DownLoadTask(map.get(url), helper, listener).start();
    }

    /**
     * 停止下载任务
     */
    public void stop(String url) {
        map.get(url).setStop(true);
    }

    /**
     * 删除下载任务
     */
    public void delete(FileInfo fileInfo) {
        map.remove(fileInfo);
        helper.deleteData(helper.getWritableDatabase(), fileInfo.getUrl());
    }

    /**
     * 重新下载任务
     */
    public void restart(String url) {
        stop(url);
        try {
            File file = new File(FILE_PATH, map.get(url).getFileName());
            if (file.exists()) {
                file.delete();
            }
            Thread.sleep(100);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        SQLiteDatabase db = helper.getReadableDatabase();
        helper.resetData(db, url);
        start(url);
    }

    /**
     * 获取当前任务状态
     */
    public boolean getCurrentState(String url) {
        return map.get(url).isDownLoading();
    }

    /**
     * 添加下载任务
     *
     * @param info 下载文件信息
     */
    public void addTask(FileInfo info) {
        //判断数据库是否已经存在这条下载信息
        SQLiteDatabase db = helper.getReadableDatabase();
        if (!helper.isExist(db, info)) {
            db = helper.getWritableDatabase();
            helper.insertData(db, info);
            map.put(info.getUrl(), info);
        } else {
            //从数据库获取最新的下载信息
            db = helper.getReadableDatabase();
            FileInfo o = helper.queryData(db, info.getUrl());
            if (!map.containsKey(info.getUrl())) {
                map.put(info.getUrl(), o);
            }
        }
    }
}
